import React, { useEffect, useState } from 'react';
import { LockOutlined, MobileOutlined } from '@ant-design/icons';
import { Button, Form, Input, message, Tabs, Image, Modal, Radio, Space } from 'antd';
import { connect, useModel } from 'umi';
import { setAuthority } from '@/utils/authority';
import './index.less';
import { debounce } from 'lodash';
import loginBg from '@/assets/login/login_bg.png';
import loginBgSmall from '@/assets/login/login_bg_small.png';
import LoginReg from './compoments/LoginReg';

const isDev = process.env.NODE_ENV === 'development';
const WebSocketUrl = process.env.WEBSOCKET_URL;
const { TabPane } = Tabs;
/**
 * window.connectModel: 全局绑定useModel('@@initialState')，给class页面使用的，为了获取用户信息的
 * 用法：采用注解的形式
 * 例子：
 @window.connectModel('initPageData', '@@initialState')
 class Authorized extends React.Component<IProps>
 ...
 获取用户信息：
 const { initPageData: { initialState } } = this.props;
 const loginInfo:any = initialState.currentUser;// 等同于原来的 getAuthority();

 *
 */
window.connectModel = (key: any, name: any) => {
  return (WrappedComponent: any) => {
    return (props: any) => {
      const model = useModel(name);
      const data = { [key]: model };
      return <WrappedComponent {...props} {...data} />;
    };
  };
};

const Login: React.FC = (props: any) => {
  let timer: any = null;
  const { dispatch } = props;
  const [loginForm] = Form.useForm();
  const [forgetForm] = Form.useForm();
  // user: 状态, dispatch: 接口调用
  const [submitting, setSubmitting] = useState(false); // 登录loading
  const [userLoginState, setUserLoginState] = useState<any>({});
  const [uuid, setUuid] = useState<number>(0);
  const [captcha, setCaptcha] = useState<string>(''); // 图形验证码图片路径
  const [isForget, setIsForget] = useState<boolean>(false); // 是否是忘记密码
  const [current, setCurrent] = useState<string>('2'); // 登录tab切换
  const [loginName, setLoginName] = useState<string>(''); // 登录名
  const [pwd, setPwd] = useState<string>(''); // 密码
  const [verifyCode, setVerifyCode] = useState<string>(''); // 图形验证码
  const [mobilePhone, setMobilePhone] = useState<string>(''); // 手机号
  const [yzm, setYzm] = useState<string>(''); // 手机验证码
  const [isRead, setIsread] = useState<boolean>(false); // 是否已读条例
  const [time, setTime] = useState<number>(60); // 倒计时
  const [isShowCode, setIsShowCode] = useState<boolean>(false); // 展示倒计时秒数
  const [password, setPassword] = useState<string>(''); // 重置密码
  const [confirmPassword, setConfirmPassword] = useState<string>(''); // 重置二次确认密码
  const [isActivePage, setIsActivePage] = useState<boolean>(false);

  // 弹窗相关数据
  const [modalVisible, setModalVisible] = useState<boolean>(false); // 身份权限选择弹窗
  const [roleList, setRoleList] = useState<any[]>([]);
  const [schOrgList, setSchOrgList] = useState<any[]>([]);
  const [activeRole, setActiveRole] = useState<number>(0);
  const [activeSchOrgId, setActiveSchOrgId] = useState<string>('');

  const [qrcodeSrc, setQrcodeSrc] = useState(''); //二维码

  const { initialState, setInitialState } = useModel('@@initialState');

  const getCaptcha = () => {
    const randomUuid = Math.random() * 1000;
    setUuid(randomUuid);
    setCaptcha(`${process.env.CAPTCHA}?uuid=${randomUuid}`);
  };

  // 页面初次加载
  useEffect(() => {
    getCaptcha();
    return () => {
      setModalVisible(false);
      setRoleList([]);
      setSchOrgList([]);
    };
  }, []);

  // 监听current  如果是1  则是扫码登陆
  useEffect(() => {
    if (current === '1') {
      dispatch({
        type: 'login/getQrCode',
        payload: {},
        callback: (res: any) => {
          const { code, data, msg } = res;
          if (code === 1) {
            setQrcodeSrc(`data:image/png;base64,${data.image}`);
            // 开启ws
            const websocket = new WebSocket(`${WebSocketUrl}loginSocket/${data.uid}`);
            websocket.onopen = (e: any) => {
              console.log(e, '>>开启');
            };
            websocket.onmessage = (e: any) => {
              console.log(e, '>>信息');
              const resultData: any = JSON.parse(e.data);
              message.success('登录成功！');
              // 将数据放入InitialState及缓存中
              setInitialState({ ...initialState, currentUser: resultData });
              setAuthority(resultData);
              // 进入系统
              window.location.href = `${window.location.origin}${isDev ? '' : `/portal`}`;
            };
            websocket.onclose = (e: any) => {
              console.log(e, '>>关闭');
            };
          } else {
            message.error(msg);
          }
        },
      });
    }
  }, [current]);

  /**切换页面 登录/激活 */
  const changePageType = () => {
    window.location.href = `${window.routerBase}register`;
  };

  // 选择角色
  const chooseRole = () => {
    dispatch({
      type: 'login/getSchAdminChooseRole',
      payload: {},
      callback: (res: any) => {
        if (res.code === 1) {
          const { roleList, schOrgList } = res.data;
          setRoleList(roleList);
          setSchOrgList(schOrgList);
          setActiveSchOrgId(schOrgList[0]?.id);
          setModalVisible(true);
        } else {
          message.error(res.msg);
        }
      },
    });
  };

  const handleSubmit = debounce(() => {
    if (!loginName) {
      message.error('请输入账号');
      return;
    }
    if (!pwd) {
      message.error('请输入密码');
      return;
    }
    if (!verifyCode) {
      message.error('请输入验证码');
      return;
    }
    // 先注释阅读协议
    if (!isRead) {
      message.error('请同意相关协议');
      return;
    }
    setSubmitting(true);

    const fromData = {
      uuid,
      captcha: verifyCode,
      username: loginName,
      password: pwd,
    };

    // 登录
    dispatch({
      type: 'login/login',
      payload: fromData,
      callback: (res: any) => {
        if (res.code === 1) {
          setAuthority(res.data);
          // 将数据放入InitialState及缓存中
          setInitialState({ ...initialState, currentUser: res.data });
          if (res.data.chooseRole) {
            // 调取接口，打开小卡片，再次确定选择的人员权限
            chooseRole();
          } else {
            message.success('登录成功！');
            // 进入系统
            window.location.href = `${window.location.origin}${isDev ? '' : `/portal`}`;
          }
        } else {
          message.error(res.msg);
          getCaptcha();
        }
        setSubmitting(false);
      },
    });
  }, 500);

  const handleSubmitMobile = debounce(() => {
    if (!mobilePhone) {
      message.error('请输入手机号');
      return;
    }
    if (!yzm) {
      message.error('请输入短信验证码');
      return;
    }
    // 先注释阅读协议
    if (!isRead) {
      message.error('请同意相关协议');
      return;
    }
    setSubmitting(true);

    const fromData = {
      mobile: mobilePhone,
      verificationCode: yzm,
    };

    // 登录
    dispatch({
      type: 'login/loginMobilePhoneEncrypted',
      payload: fromData,
      callback: (res: any) => {
        if (res.code === 1) {
          setAuthority(res.data);
          // 将数据放入InitialState及缓存中
          setInitialState({ ...initialState, currentUser: res.data });
          if (res.data.chooseRole) {
            // 调取接口，打开小卡片，再次确定选择的人员权限
            chooseRole();
          } else {
            message.success('登录成功！');
            // 进入系统
            window.location.href = `${window.location.origin}${isDev ? '' : `/portal`}`;
          }
        } else {
          message.error(res.msg);
        }
        setSubmitting(false);
      },
    });
  }, 500);

  // 切换登录
  const changeTabs = (key: any) => {
    setCurrent(key);
  };

  // 输入用户名
  const onChangeLoginName = (e: any) => {
    setLoginName(e.target.value);
  };
  // 输入密码
  const onChangePwd = (e: any) => {
    setPwd(e.target.value);
  };
  // 图形验证码
  const onChangeVerifyCode = (e: any) => {
    setVerifyCode(e.target.value);
  };

  // 输入手机号
  const onChangeMobilePhone = (e: any) => {
    setMobilePhone(e.target.value);
  };
  // 输入验证码
  const onChangeYzm = (e: any) => {
    setYzm(e.target.value);
  };

  // 获取次数
  const getCount = () => {
    dispatch({
      type: 'userLogin/getMessageLimit',
      payload: { mobilePhone },
      callback: (response: any) => {
        if (response.code === 1) {
          message.warning(response.data, 5);
        } else {
          message.error(response.msg);
        }
      },
    });
  };
  // 发送验证码
  const loginYzm = debounce((type: number) => {
    // type   1:验证码登录发送验证码   2：忘记密码发送验证码
    if (typeof mobilePhone === 'undefined' || mobilePhone === null || mobilePhone === '') {
      message.info('请输入手机号');
      return;
    }
    if (isShowCode) {
      // 倒计时未结束,不能重复点击
      return;
    }
    if (type === 1) {
      dispatch({
        type: 'login/sendYzm',
        payload: { mobile: mobilePhone },
        callback: (res: any) => {
          const { code, msg } = res;
          if (code === 1) {
            getCount();
            setIsShowCode(true);
            timer = setInterval(() => {
              setTime((preSecond) => {
                if (preSecond <= 1) {
                  setIsShowCode(false);
                  clearInterval(timer);
                  // 重置秒数
                  return 60;
                }
                return preSecond - 1;
              });
            }, 1000);
          } else {
            message.error(msg);
          }
        },
      });
    } else {
      dispatch({
        type: 'login/sendModifyYzm',
        payload: { mobile: mobilePhone },
        callback: (res: any) => {
          const { code, msg } = res;
          if (code === 1) {
            getCount();
            setIsShowCode(true);
            timer = setInterval(() => {
              setTime((preSecond) => {
                if (preSecond <= 1) {
                  setIsShowCode(false);
                  clearInterval(timer);
                  // 重置秒数
                  return 60;
                }
                return preSecond - 1;
              });
            }, 1000);
          } else {
            message.error(msg);
          }
        },
      });
    }
  }, 500);

  // 忘记密码
  const onClickForget = () => {
    setIsForget(true);
    setIsShowCode(false); // 强制关闭倒计时
    // 重置信息
    setMobilePhone('');
    setYzm('');
    setPassword('');
    setConfirmPassword('');
    loginForm.setFieldsValue({
      mobilePhone: '',
      yzm: '',
      password: '',
      confirmPassword: '',
    });
  };
  // 返回登录
  const onClickBack = () => {
    setIsForget(false);
    setIsShowCode(false); // 强制关闭倒计时
    // 重置信息
    setMobilePhone('');
    setYzm('');
    setPassword('');
    setConfirmPassword('');
    forgetForm.setFieldsValue({
      mobilePhone: '',
      yzm: '',
      password: '',
      confirmPassword: '',
    });
  };

  // 输入重置密码
  const onChangePassword = (e: any) => {
    setPassword(e.target.value);
  };
  // 输入二次重置密码
  const onChangeConfirmPassword = (e: any) => {
    setConfirmPassword(e.target.value);
  };

  // 提交重置密码
  const handleSubmitForget = debounce(() => {
    setSubmitting(true);
    const params: any = {
      password,
      passwordAgain: confirmPassword,
      mobile: mobilePhone,
      verificationCode: yzm,
    };

    // 修改密码
    dispatch({
      type: 'login/forgetPwd',
      payload: { ...params, uuid },
      callback: (res: any) => {
        if (res.code === 1) {
          message.success('修改密码成功！');
          onClickBack();
        } else {
          message.error(res.msg);
        }
        setSubmitting(false);
      },
    });
  }, 500);

  // 选择权限弹窗ok
  const handleOk = () => {
    dispatch({
      type: 'login/updateSchUserToken',
      payload: {
        type: activeRole,
        schOrgId: activeSchOrgId,
      },
      callback: (res: any) => {
        if (res.code === 1) {
          message.success('登录成功！');
          // 将数据放入InitialState及缓存中
          const _initialState: any = { ...initialState };
          _initialState.currentUser.currentRoleId = res.data.currentRoleId;
          setAuthority(_initialState.currentUser);
          setInitialState({ ..._initialState });
          // 进入系统
          window.location.href = `${window.location.origin}${isDev ? '' : `/portal`}`;
        } else {
          message.error(res.msg);
        }
        setSubmitting(false);
      },
    });
  };
  // 取消权限弹窗ok
  const handleCancel = () => {
    setModalVisible(false);
  };

  // 选择权限radio
  const changeRadio = (e: any) => {
    setActiveSchOrgId(e.target.value);
  };

  const changeActiveRole = (i: number) => {
    setActiveRole(i);
  };

  return (
    <div className="login_wrap">
      <div className="loginBg" style={{ backgroundImage: `url(${loginBg})` }}>
        <div className="login_main">
          <img className="login_left_img" src={loginBgSmall} />
          <div className="login_right">
            {/* <div className="grayTopTxt">
							<a href="javascript:;" onClick={changePageType}>
								{isActivePage ? '已激活去登录' : '去激活'}
							</a>
						</div> */}

            <div className="login_title">伯乐寻骥</div>
            {isForget ? (
              <Form form={forgetForm} className="login_form">
                <Form.Item name="mobilePhone" rules={[{ required: true, message: '请输入手机号' }]}>
                  <Input
                    prefix={<MobileOutlined />}
                    onChange={onChangeMobilePhone}
                    placeholder="输入手机号"
                    value={mobilePhone}
                  />
                </Form.Item>
                <Form.Item name="yzm" rules={[{ required: true, message: '请输入验证码' }]}>
                  <Input
                    prefix={<LockOutlined />}
                    onChange={onChangeYzm}
                    placeholder="输入验证码"
                    value={yzm}
                    suffix={
                      <div className="sendYZM">
                        <Button
                          type="link"
                          onClick={() => {
                            loginYzm(2);
                          }}
                        >
                          {isShowCode ? `${time}秒` : '获取验证码'}
                        </Button>
                      </div>
                    }
                  />
                </Form.Item>
                <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
                  <Input.Password
                    prefix={<LockOutlined />}
                    onChange={onChangePassword}
                    placeholder="输入密码"
                    value={password}
                  />
                </Form.Item>
                <Form.Item
                  name="confirmPassword"
                  rules={[{ required: true, message: '请再次输入密码' }]}
                >
                  <Input.Password
                    prefix={<LockOutlined />}
                    onChange={onChangeConfirmPassword}
                    placeholder="再次输入密码"
                    value={confirmPassword}
                  />
                </Form.Item>
                <div className="forget">
                  <span className="btn" onClick={onClickBack}>
                    返回登录
                  </span>
                </div>
                <Button
                  className="login_form_button"
                  loading={submitting}
                  onClick={handleSubmitForget}
                >
                  重置密码
                </Button>
              </Form>
            ) : (
              <Form form={loginForm} className="login_form">
                <Tabs activeKey={current} onChange={changeTabs} className="login_tabs">
                  

                  <TabPane tab="账号密码登录" key="2">
                    <Form.Item
                      name="loginName"
                      rules={[{ required: true, message: '请输入登录账号' }]}
                    >
                      <Input
                        prefix={<MobileOutlined />}
                        onChange={onChangeLoginName}
                        placeholder="输入登录名/手机号"
                        value={loginName}
                      />
                    </Form.Item>
                    <Form.Item name="pwd" rules={[{ required: true, message: '请输入密码' }]}>
                      <Input.Password
                        prefix={<LockOutlined />}
                        onChange={onChangePwd}
                        placeholder="输入密码"
                        value={pwd}
                      />
                    </Form.Item>
                    <div className="verifyCode">
                      <Form.Item
                        name="verifyCode"
                        rules={[{ required: true, message: '请输入验证码' }]}
                      >
                        <Input
                          onChange={onChangeVerifyCode}
                          placeholder="输入验证码"
                          value={verifyCode}
                        />
                      </Form.Item>
                      <div className="captcha">
                        <img
                          onClick={() => {
                            getCaptcha();
                          }}
                          src={captcha}
                        />
                      </div>
                    </div>

                    <div className="forget">
                      <span className="btn" onClick={onClickForget}>
                        忘记密码
                      </span>
                    </div>
                    <Button
                      className="login_form_button"
                      loading={submitting}
                      onClick={handleSubmit}
                    >
                      登录
                    </Button>
                  </TabPane>

                  <TabPane tab="手机号验证码登录" key="3">
                    <Form.Item
                      name="mobilePhone"
                      rules={[{ required: true, message: '请输入手机号' }]}
                    >
                      <Input
                        prefix={<MobileOutlined />}
                        onChange={onChangeMobilePhone}
                        placeholder="输入手机号"
                        value={mobilePhone}
                      />
                    </Form.Item>
                    <Form.Item name="yzm" rules={[{ required: true, message: '请输入验证码' }]}>
                      <Input
                        prefix={<LockOutlined />}
                        onChange={onChangeYzm}
                        placeholder="输入验证码"
                        value={yzm}
                        suffix={
                          <div className="sendYZM">
                            <Button
                              type="link"
                              onClick={() => {
                                loginYzm(1);
                              }}
                            >
                              {isShowCode ? `${time}秒` : '获取验证码'}
                            </Button>
                          </div>
                        }
                      />
                    </Form.Item>
                    <Button
                      className="login_form_button mt40"
                      loading={submitting}
                      onClick={handleSubmitMobile}
                    >
                      登录
                    </Button>
                  </TabPane>
                </Tabs>
                {/* 登录条例组件 */}
                {(current === '2' || current === '3') && (
                  <LoginReg
                    onCheckChange={(bol) => {
                      setIsread(bol);
                    }}
                  />
                )}
              </Form>
            )}
          </div>
        </div>
      </div>

      <Modal
        title="身份权限选择"
        className="jurisdictionModal"
        width={640}
        visible={modalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确认"
        cancelText="取消"
      >
        <div className="container">
          <div className="chooseType">
            <div className="type_left">
              <span className="require">*</span>
              <span className="labelText">身份选择：</span>
            </div>
            <div className="type_right">
              {roleList &&
                roleList.map((item: any, index: number) => {
                  return (
                    <div
                      className={`item ${activeRole === index ? 'active' : ''}`}
                      onClick={() => {
                        changeActiveRole(index);
                      }}
                    >
                      {item.name}
                    </div>
                  );
                })}
            </div>
          </div>
          {activeRole === 0 && (
            <div className="tip">
              管理员身份：主要负责<span className="nitoce">学生信息、资讯</span>等功能管理
            </div>
          )}
          {activeRole === 1 && (
            <div className="tip">
              老师身份：主要负责<span className="nitoce">任务、育匠</span>等功能管理
            </div>
          )}
          {activeRole === 0 && (
            <div className="chooseJurisdiction">
              <div className="jurisdiction_left">
                <span className="require">*</span>
                <span className="labelText">权限选择：</span>
              </div>
              <div className="jurisdiction_right">
                <Radio.Group onChange={changeRadio} value={activeSchOrgId}>
                  <Space direction="vertical">
                    {schOrgList &&
                      schOrgList.length > 0 &&
                      schOrgList.map((item: any, i: number) => {
                        return <Radio value={item.id}>{item.name}</Radio>;
                      })}
                  </Space>
                </Radio.Group>
              </div>
            </div>
          )}
          {activeRole === 0 && (
            <div className="tip">
              选择后对应功能数据显示为<span className="nitoce">当前组织及以下</span>的
            </div>
          )}
        </div>
      </Modal>
    </div>
  );
};

export default connect(({ user, loading }: { user: any; loading: any }) => ({
  user,
  loading: loading.models.user,
}))(Login);
